package chixing.day19.work2;

import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TaskManager2 {
    Map<String, Task> taskMap = new HashMap<>();
    Map<String, List<LocalDateTime>> taskRecord = new HashMap<>();

    public TaskManager2() {
        // 初始化预定义任务的执行记录
        taskRecord.put("SyncStockTask", new ArrayList<>());
        taskRecord.put("SendInterviewTask", new ArrayList<>());
        taskRecord.put("GenerateReportTask", new ArrayList<>());
    }

    public void registerTask(Task task) {
        taskMap.put(task.getName(), task);
        taskRecord.putIfAbsent(task.getName(), new ArrayList<>());
    }

    public Task getTaskByName(String name) {
        return taskMap.get(name);
    }

    // 单个任务执行
    public void executeTask(String name) {
        Task task = getTaskByName(name);
        if (task != null) {
            task.execute();
            LocalDateTime now = LocalDateTime.now();
            taskRecord.computeIfAbsent(name, k -> new ArrayList<>()).add(now);
        } else {
            System.out.println("任务 " + name + " 不存在，无法执行");
        }
    }

    // 批量执行任务
    public void executeTasks(List<String> taskNames) {
        System.out.println("开始批量执行任务...");
        for (String name : taskNames) {
            System.out.println("执行任务: " + name);
            executeTask(name);
        }
        System.out.println("批量任务执行完成。");
    }


    // 查询所有任务的最新一次执行时间
    public void printAllLatestExecutionTime() {
        System.out.println("所有任务的最新执行时间:");
        System.out.println("----------------------------------------");
        for (Map.Entry<String, List<LocalDateTime>> entry : taskRecord.entrySet()) {
            String taskName = entry.getKey();
            List<LocalDateTime> history = entry.getValue();

            if (history != null && !history.isEmpty()) {
                LocalDateTime latestTime = history.get(history.size() - 1);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                System.out.println(taskName + ": " + latestTime.format(formatter));
            } else {
                System.out.println(taskName + ": 从未执行");
            }
        }
        System.out.println("----------------------------------------");
    }

    // 获取单个任务的执行历史
    public void printHistory(String name) {
        List<LocalDateTime> history = taskRecord.get(name);
        if (history != null && !history.isEmpty()) {
            System.out.println("任务 " + name + " 的执行历史：");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (LocalDateTime time : history) {
                System.out.println(time.format(formatter));
            }
        } else {
            System.out.println("任务 " + name + " 没有执行历史");
        }
    }

    // 将执行历史保存到CSV文件
    public void saveHistoryToCSV(String filename) {
        try (FileWriter writer = new FileWriter(filename)) {
            // 写入CSV头部
            writer.append("TaskName,ExecutionTime\n");

            // 遍历所有任务的执行历史
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (Map.Entry<String, List<LocalDateTime>> entry : taskRecord.entrySet()) {
                String taskName = entry.getKey();
                List<LocalDateTime> history = entry.getValue();

                if (history != null && !history.isEmpty()) {
                    for (LocalDateTime time : history) {
                        writer.append(taskName)
                                .append(",")
                                .append(time.format(formatter))
                                .append("\n");
                    }
                }
            }

            System.out.println("执行历史已保存到 " + filename);
        } catch (IOException e) {
            System.err.println("保存执行历史到CSV文件时出错: " + e.getMessage());
        }
    }

    // 将执行历史保存为简单JSON格式
    public void saveHistoryToJSON(String filename) {
        try (FileWriter writer = new FileWriter(filename)) {
            writer.append("{\n");
            writer.append("  \"taskHistory\": {\n");

            boolean firstTask = true;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            for (Map.Entry<String, List<LocalDateTime>> entry : taskRecord.entrySet()) {
                if (!firstTask) {
                    writer.append(",\n");
                }
                firstTask = false;

                String taskName = entry.getKey();
                List<LocalDateTime> history = entry.getValue();

                writer.append("    \"").append(taskName).append("\": [");

                if (history != null && !history.isEmpty()) {
                    boolean firstTime = true;
                    for (LocalDateTime time : history) {
                        if (!firstTime) {
                            writer.append(",");
                        }
                        firstTime = false;
                        writer.append("\n      \"").append(time.format(formatter)).append("\"");
                    }
                    writer.append("\n    ]");
                } else {
                    writer.append("]");
                }
            }

            writer.append("\n  }\n");
            writer.append("}\n");

            System.out.println("执行历史已保存到 " + filename);
        } catch (IOException e) {
            System.err.println("保存执行历史到JSON文件时出错: " + e.getMessage());
        }
    }
}
